﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SHomeWorkshop.LunarConcept.ModifingManager;
using System.Windows;
using SHomeWorkshop.LunarConcept.Controls;
using SHomeWorkshop.LunarConcept.Tools;
using System.Windows.Media;

namespace SHomeWorkshop.LunarConcept.Commands.TextCommands
{
    /// <summary>
    /// 创建时间：2012年7月24日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：批量为部件设置过渡色（前景色统一为白色，因此最好用与白色相区别的浅色背景色，终点色总是接近黑色）。
    /// 
    /// 　　　　　提供自定义字符串命令的执行方法。
    ///           条件：⑴类名必须以“_TC”开头，否则会无法调用。
    ///                   类名即内置命令文本，用户输入的命令文本将被转换（通过映射表）成内置命令，
    ///                   根据内置命令字符串（即类名），找到类，并调用必须实现的下列方法：
    ///                 ⑵类必须实现带一个string型参数的:
    ///                   static string Execute(string parameters)方法，
    ///                   此方法必须自行处理parameters中以半角空格分隔的命令参数列表（当然，如果不需要，也可不处理）。
    /// </summary>
    [Tools.TextCommandAttribute("/tc/transcolors/gds/过渡色/", Enums.TextCommandType.Appearance, "批量设置部件过渡色")]
    public class _TCSetTransColorsAtWidgets
    {
        /// <summary>
        /// [静态方法]
        /// </summary>
        /// <param name="parameters">字符串形式的参数列表（参数间用半角空格分隔）。</param>
        /// <returns>顺利执行返回string.Empty，否则返回错误信息字符串。</returns>
        public static string Execute(string parameters)
        {
            if (parameters != null && parameters.Trim() == "?")
            {
                TextCommandHelp.ShowHelp("_TCSetTransColorsAtWidgets");
                return string.Empty;
            }

            if (Globals.MainWindow == null) return "　　未找到主窗口。";

            LunarConcept.Controls.EditorManager manager = Globals.MainWindow.EditorManager;
            if (manager == null) return "　　未找到主窗口的页面管理器。";

            PageEditor mainPe = manager.GetMainSelectedPageEditor();
            if (mainPe == null) return "　　未找到选定页面。";

            List<Widgets.Widget> selectedWidgets = mainPe.GetSelectedWidgetsList();
            if (selectedWidgets.Count <= 0) return "　　未选定部件。";

            char[] separator = new char[1];
            separator[0] = ' ';

            string[] paras = parameters.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            if (paras.Length < 1) return "　　传入的参数个数不正确。此命令首参数应指定过渡色起始纯色，次参数指定垂直或水平应用过渡色。";

            Brush newBrush = BrushManager.GetBrushByEnglishName(paras[0].Trim().ToLower());
            if (newBrush == null)
            {
                newBrush = BrushManager.GetBrushByChineseName(paras[0].Trim().ToLower());
            }

            if (newBrush == null)
            {
                return "　　没有这种色彩：" + paras[0];//按中文名称也找不到。
            }

            if (paras.Length >= 2)
            {
                switch (paras[1])
                {
                    case "v":
                    case "vertical":
                    case "cz":
                    case "z":
                    case "zx":
                    case "s":
                    case "sx":
                    case "sz":
                    case "垂直":
                    case "纵":
                    case "纵向":
                    case "竖":
                    case "竖向":
                    case "竖直":
                        {
                            selectedWidgets.Sort(new Tools.WidgetCenterYCompareClass());//按横坐标排序。
                            break;
                        }
                    case "h":
                    case "horizontal":
                    case "hx":
                    case "sp":
                    case "横":
                    case "横向":
                    case "水平":
                        {
                            selectedWidgets.Sort(new Tools.WidgetCenterXCompareClass());//按纵坐标排序
                            break;
                        }
                    default:
                        {
                            return "　　第二参数非法。省略第二参数可按横向填充过渡色。纵向则使用单字母【v】作第二参数。";
                        }
                }
            }
            else
            {
                //如果省略了参数，尝试智能判断。

                double minleft = double.MaxValue;
                double mintop = double.MaxValue;
                double maxright = 0;
                double maxbottom = 0;

                foreach (Widgets.Widget w in selectedWidgets)
                {
                    Rect rect = w.RealRect;
                    Point center = new Point(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2);

                    if (center.X < minleft) minleft = center.X;
                    if (center.X > maxright) maxright = center.X;
                    if (center.Y < mintop) mintop = center.Y;
                    if (center.Y > maxbottom) maxbottom = center.Y;
                }

                double width = maxright - minleft;
                double height = maxbottom - mintop;

                if (width < 0 || height < 0)
                {
                    selectedWidgets.Sort(new Tools.WidgetCenterXCompareClass());//意外情况，按横向填充
                }
                else
                {
                    if (width > height)
                    {
                        selectedWidgets.Sort(new Tools.WidgetCenterXCompareClass());
                    }
                    else
                    {
                        selectedWidgets.Sort(new Tools.WidgetCenterYCompareClass());//按纵向排列填充
                    }
                }
            }

            SolidColorBrush solidBrush = newBrush as SolidColorBrush;
            if (solidBrush == null)
            {
                return "　　指定的背景色必须是纯色（浅色较好）。";
            }

            ModifingInfo info = new ModifingInfo();
            info.ModifingDescription = "批量设置部件过渡色";
            manager.GetSelectedPageEditorStatus(info);
            manager.GetSelectedWidgetStatus_Old(info);
            manager.GetSelectedWidgetStatus_New(info);

            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

            float f = (float)(1f / selectedWidgets.Count);
            int i = selectedWidgets.Count + 1;

            foreach (Widgets.Widget w in selectedWidgets)
            {
                i--;

                Color newColor = solidBrush.Color * i * f; newColor.A = 255;
                SolidColorBrush newBackColor = new SolidColorBrush(newColor);

                Action actSetBackColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetBackColor,
                    BrushManager.GetName(w.WidgetBackColor), BrushManager.GetName(newBackColor));
                w.WidgetBackColor = newBackColor;
                mi.AddAction(actSetBackColor);

                if (w.WidgetForeColor != Brushes.White)
                {
                    Action actSetForeColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
                           BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(Brushes.White));
                    w.WidgetForeColor = Brushes.White;
                    mi.AddAction(actSetForeColor);
                }

                if (w.WidgetLineColor != Brushes.Transparent)
                {
                    Action actSetLineColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetLineColorTag,
                           BrushManager.GetName(w.WidgetLineColor), BrushManager.GetName(Brushes.Transparent));
                    w.WidgetLineColor = Brushes.Transparent;
                    mi.AddAction(actSetLineColor);
                }
            }

            manager.RegisterModifingItem(mi);
            return string.Empty;
        }
    }
}
